//
//  GReminder.m
//  FootPrint
//
//  Created by alex tao on 3/25/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "GReminder.h"

@implementation GReminder

+ (UILocalNotification*) notificationForKey:(NSString*)key {
    return [GReminder notificationForKey:key andSubKey:nil];
}

+ (UILocalNotification*) notificationForKey:(NSString*)key andSubKey:(NSString*)subKey
{
    if (nil == key) {
        return nil;
    }
    NSArray * notifies = [[UIApplication sharedApplication] scheduledLocalNotifications];
    for (UILocalNotification * notify in notifies) {
        if ([key isEqualToString:[notify.userInfo objectForKey:@"key"]]) {
            if (subKey) {
                if (![subKey isEqualToString:[notify.userInfo objectForKey:@"subKey"]]) {
                    return nil;
                }
            }
            return notify;
        }
    }
    return nil;
}


+ (UILocalNotification*) setReminder:(NSDictionary*)msg at:(NSDate*)date withKey:(NSString*)key {
    return [GReminder setReminder:msg at:date withKey:key andSubKey:nil];
}

+ (UILocalNotification*) setReminder:(NSDictionary*)msg at:(NSDate*)date withKey:(NSString*)key andSubKey:(NSString*)subKey
{
    if (nil == key) {
        return nil;
    }
    UILocalNotification * notify = [GReminder notificationForKey:key andSubKey:subKey];
    if (notify) {
        [[UIApplication sharedApplication] cancelLocalNotification:notify];
    }
    
    notify = [[[UILocalNotification alloc] init] autorelease];
    notify.timeZone = [NSTimeZone defaultTimeZone];
    notify.soundName = UILocalNotificationDefaultSoundName;
    
    NSMutableDictionary * info = [NSMutableDictionary dictionaryWithDictionary:msg];
    [info setObject:key forKey:@"key"];
    if (subKey) {
        [info setObject:subKey forKey:@"subKey"];
    }
    notify.userInfo = info;
    
    notify.alertBody = [msg objectForKey:@"msg"];
    notify.fireDate = date;
    [[UIApplication sharedApplication] scheduleLocalNotification:notify];
    
    return notify;
}

+ (void) cancelReminderWithKey:(NSString*)key {
    [GReminder cancelReminderWithKey:key andSubKey:nil];
}

+ (void) cancelReminderWithKey:(NSString*)key andSubKey:(NSString*)subKey {
    UILocalNotification * notify = [GReminder notificationForKey:key andSubKey:subKey];
    if (notify) {
        [[UIApplication sharedApplication] cancelLocalNotification:notify];
    }
}

+ (void) cancelAllReminder {
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

@end
